"use strict";

const Controller = require("egg").Controller;

class ListController extends Controller {
  // 添加
  async create() {
    // 解析服务端
    const { service } = this.ctx;
    const body = this.ctx.request.body;
    // 接收前端传参
    const { name, tel, address } = body;
    console.log(name, tel, address);
    // 非空验证
    if (name && tel && address) {
      // 调用服务端查找功能
      const findres = await service.list.find(body);

      // 判断是否存在
      if (!findres) {
        // 调用服务端注册功能
        await service.list.Addlist(body);
        this.ctx.body = {
          code: "SUCCESS",
          msg: "添加成功",
          status: 200,
        };
      } else {
        this.ctx.body = {
          code: "FIAL",
          msg: "该数据已经存在，请重新添加",
          status: 417,
        };
      }
    } else {
      this.ctx.body = {
        code: "FIAL",
        msg: "添加信息信息不能为空",
        status: 417,
      };
    }
  }
  // 删除
  async destroy() {
    // 解析服务端
    const { service } = this.ctx;
    const { id } = this.ctx.params;
    console.log(id);
    if (id) {
      await service.list.destroy(id);
      this.ctx.body = {
        code: "SUCCESS",
        msg: "删除成功",
        status: 200,
      };
    } else {
      this.ctx.body = {
        code: "FIAL",
        msg: "缺少参数",
        status: 417,
      };
    }
  }
  // 编辑
  async update() {
    // 解析服务端
    const { service } = this.ctx;
    // 接收前端传参
    let body = this.ctx.request.body;
    const { id } = this.ctx.params;
    const { name, tel, address } = body;
    const row = {
      id: id,
      name: name,
      tel: tel,
      address: address,
    };
    // 非空验证
    if (name && tel && address) {
      // 调用服务端编辑功能
      await service.list.update(row);
      this.ctx.body = {
        code: "SUCCESS",
        msg: "编辑成功",
        status: 200,
      };
    } else {
      this.ctx.body = {
        code: "FIAL",
        msg: "编辑信息信息不能为空",
        status: 417,
      };
    }
  }
  // 查找
  async index() {
    // 解析服务端
    const { service } = this.ctx;
    const res = await service.list.index();
    this.ctx.body = {
        code: "SUCCESS",
        msg: "查找所有数据成功",
        status: 200,
        alldata: res
    };
  }
  async show() {
    // 解析服务端
    const { service } = this.ctx;
    const { id } = this.ctx.params;
    console.log(id);
    if (id) {
      const res = await service.list.index(id);
      this.ctx.body = {
        code: "SUCCESS",
        msg: "查找单条数据成功",
        status: 200,
        onedata: res
      };
      return;
    }
  }
}

module.exports = ListController;
